package jp.dev7.android.http;

import java.io.IOException;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.SSLSocketFactory;

/**
 * SSLSocketのファクトリ.
 * 
 * @author narazaki.daishi
 */
public class NoneSSLVerifierSSLSocketFactory extends SSLSocketFactory {

    /** ssl. */
    private final SSLContext context;

    /**
     * コンストラクタ。
     * 
     * @param sslContext
     *            -
     * @throws KeyStoreException
     *             -
     * @throws NoSuchAlgorithmException
     *             -
     * @throws UnrecoverableKeyException
     *             -
     * @throws KeyManagementException
     *             -
     */
    public NoneSSLVerifierSSLSocketFactory(SSLContext sslContext)
            throws KeyManagementException, UnrecoverableKeyException,
            NoSuchAlgorithmException, KeyStoreException {
        super((KeyStore) null);
        this.context = sslContext;
    }

    /**
     * 作成する。
     * 
     * @return -
     * @throws Exception
     *             -
     */
    public static NoneSSLVerifierSSLSocketFactory create() throws Exception {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkServerTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
                // empty
            }

            public void checkClientTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
                // empty
            }
        } }, null);

        return new NoneSSLVerifierSSLSocketFactory(sslContext);
    }

    @Override
    public Socket createSocket() throws IOException {
        return context.getSocketFactory().createSocket();
    }
}
